package com.ys.controller.api.outer;

import com.ys.entity.business.TbBaseInfo;
import com.ys.entity.business.TbPlatformServicePayAccount;
import com.ys.entity.finance.*;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.hr.ThrOperateCompanyBankInfo;
import com.ys.entity.hr.ThrTransparencyProgramItem;
import com.ys.entity.hr.ThrVatApplyDetail;
import com.ys.entity.report.ReFinanceExamine;
import com.ys.entity.sys.TbCompanyBankInfo;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.base.TransactionTypeEnum;
import com.ys.enume.finance.PaymentEnum;
import com.ys.enume.finance.TcwFinancialTransactionFlowEnum;
import com.ys.enume.finance.TcwOperateFrozenRunningEnum;
import com.ys.enume.finance.TcwWanliOtherPaymentEnum;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.mapper.finance.TcwOperateCompanyPrepaymentMapper;
import com.ys.mapper.finance.TcwWanliPrepaymentPoolingMapper;
import com.ys.mapper.hr.HrMapper;
import com.ys.mapper.hr.ThrOperateCompanyApplyMapper;
import com.ys.mapper.report.ReFinanceExamineMapper;
import com.ys.service.business.*;
import com.ys.service.finance.TcwAccountCountForCompanyService;
import com.ys.service.finance.TcwAccountCountForWanliService;
import com.ys.service.finance.TcwFinancialTransactionFlowService;
import com.ys.service.finance.TcwOperateCompanyPrepaymentService;
import com.ys.util.CheckUtil;
import com.ys.util.DateUtil;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/api/outer/apiOuterDemoLzmLiuSui")
public class ApiOuterDemoLzmLiuSuiController {

    private static final Logger logger = LoggerFactory.getLogger(ApiOuterDemoLzmLiuSuiController.class);

	@Autowired
	private TcwAccountDetailedForCompanyService tcwAccountDetailedForCompanyService;

	@Autowired
	private TcwAccountCountForWanliService tcwAccountCountForWanliService;

	@Autowired
	private TcwFinancialTransactionFlowService tcwFinancialTransactionFlowService;

	@Autowired
	private ReFinanceExamineMapper reFinanceExamineMapper;


	@Autowired
	private TcwOperateCompanyPrepaymentMapper tcwOperateCompanyPrepaymentMapper;

	@Autowired
	private TcwAccountCountForCompanyService tcwAccountCountForCompanyService;

	@Autowired
	private TcwWanliPrepaymentPoolingMapper tcwWanliPrepaymentPoolingMapper;


	@Autowired
	private ThrOperateCompanyApplyMapper thrOperateCompanyApplyMapper;


	@Autowired
	private TcwOperateCompanyPrepaymentService tcwOperateCompanyPrepaymentService;

	@Autowired
	private CheckUtil checkUtil;


	@Autowired
	private HrMapper hrMapper;

	/**
	 * 手动反刷运营公司流水
	 */
	@RequestMapping("/test1")
	@ResponseBody
	public R test1(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			//

			List<TcwAccountDetailedForCompany> list = new TcwAccountDetailedForCompany()
					.where("A.Id IN(" +

//							"1544593," +
//							"1545158," +
//							"1545162," +
//							"1545164," +
							"1546038" +
							")")
					//.where("A.DJySj BETWEEN '2024-08-22 08:00:00' AND '2024-08-22 23:59:59'")
					//.where("A.VBz LIKE '%WFWB-241205-1002%'")
					.queryList();
			for(TcwAccountDetailedForCompany item:list){
				System.out.println(item.getVgsbm()+":"+ item.getFje() );
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
						item.getVgsbm(),item.getVgsjc(),
						item.getVgsbmp(),item.getVgsjcp(),
						item.getVjylx(),
						BigDecimal.ZERO.subtract(item.getFje()),
						item.getDjysj(),
						item.getDshsj(),
						item.getVbz()+"，（反刷流水）",
						item.getMbid(),item.getWriteTime() );

			}
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}



	/**
	 * 手动反刷万里汇流水
	 */
	@RequestMapping("/test2")
	@ResponseBody
	public R test2(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			//
			List<TcwAccountCountForWanli> list = new TcwAccountCountForWanli()
					//.where("A.Id IN(1577,1578,1579,1580,1581,1582,1583,1584)")
					.setDocumentBid("WFWB-241205-1002")
					//.where("A.DJySj BETWEEN '2024-08-22 08:00:00' AND '2024-08-22 23:59:59'")
					.queryList();
			for(TcwAccountCountForWanli item:list){
				tcwAccountCountForWanliService.add(false,
						item.getDepositPlatformCode(),item.getExchangeRateCode()
						,item.getDocumentType(),item.getDocumentBid(),BigDecimal.ZERO.subtract(item.getAccountCount()),item.getRemark()+"，（反刷流水）"
				);

			}
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}



	/**
	 * 手动反刷财务流水
	 */
	@RequestMapping("/test4")
	@ResponseBody
	public R test4(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			//
			List<TcwFinancialTransactionFlow> list = new TcwFinancialTransactionFlow()
					.where("A.Id IN(1524,1525,1526)")
					.queryList();
			for(TcwFinancialTransactionFlow item:list){
				tcwFinancialTransactionFlowService.add(false, item.getCompanyBankInfoId(), item.getTransactionTypeBid(),
						item.getVyhzhmc(), item.getVkhh(), item.getVyhzh(),
						BigDecimal.ZERO.subtract(item.getOriginalTransactionAmount()),
						item.getOccurTime(), item.getAuditingTime(), item.getWriteTime(), item.getRemark()+"，（反刷流水）",
						item.getFromType(), item.getFromId());
			}
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}



	/**
	 * 手动反刷解冻
	 */
	@RequestMapping("/test6")
	@ResponseBody
	public R test6(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			tcwAccountCountForCompanyService.frozen("GS0277", new BigDecimal(2890.00),
					TcwOperateFrozenRunningEnum.DocumentType.TCG_PurchaseByOrder.value,
					181L,
					"CGDD-241224-1068",
					"由于bug本该订单已完成的订单被计划取消，现在重新冻结计划取消时多解冻的账户资金");
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}



	/**
	 * 手动刷万里汇外币付款
	 */
	@RequestMapping("/test3")
	@ResponseBody
	public R test3(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			String bid = "WFWB-241205-1002";

			TcwWanliOtherPayment entity = new TcwWanliOtherPayment().setBid(bid).queryFirst();
			List<TcwWanliOtherPaymentItem> listTcwWanliOtherPaymentItem = new TcwWanliOtherPaymentItem().setPbid(bid).queryList();
			{
				Date now = new Date();
				// 添加账户流水
				for(TcwWanliOtherPaymentItem detail : listTcwWanliOtherPaymentItem) {

					String vgsbmp = detail.getVyhzhmc();
					String vgsjcp = detail.getVyhzhmc();

					// 更新对应单据的支付状态
					if (entity.getPayType() == TcwWanliOtherPaymentEnum.PayType.TOUMING.value) {
						ThrTransparencyProgramItem sourceEntity = new ThrTransparencyProgramItem().setId(detail.getRelativeId()).queryFirst();
						sourceEntity.setStatePay(PaymentEnum.StatePay.SUCCESS.value);
						//thrTransparencyProgramItemMapper.update(sourceEntity);

						TbPlatformServicePayAccount tbPlatformServicePayAccount = new TbPlatformServicePayAccount().setId(sourceEntity.getPtId()).queryFirst();
						vgsbmp = tbPlatformServicePayAccount.getBid();
						vgsjcp = tbPlatformServicePayAccount.getVyhzhmc();
					} else if (entity.getPayType() == TcwWanliOtherPaymentEnum.PayType.VAT.value) {
						ThrVatApplyDetail sourceEntity = new ThrVatApplyDetail().setId(detail.getRelativeId()).queryFirst();
						sourceEntity.setStatePay(PaymentEnum.StatePay.SUCCESS.value);
						//thrVatApplyDetailMapper.update(sourceEntity);

						vgsbmp = sourceEntity.getVatNo();

					} else if (entity.getPayType() == TcwWanliOtherPaymentEnum.PayType.OTHER.value) {
						TcwPartnerWbAccount sourceEntity = new TcwPartnerWbAccount().setId(detail.getRelativeId()).queryFirst();

						vgsbmp = sourceEntity.getCode();
						vgsjcp = sourceEntity.getVyhzhmc();

					}

					String vgsbm = detail.getVgsbm();
					ThrOperateCompanyApply thrOperateCompanyApply = new ThrOperateCompanyApply().setVgsbm(vgsbm).queryFirst();

					// 添加运营公司账户流水
					String vgsjc = thrOperateCompanyApply.getVgsjc();
					String vjylx = detail.getVjylx();
					BigDecimal fje = detail.getAmount().add(detail.getFee()).multiply(entity.getExchangeRate()).negate();
					Date djysj = now;
					Date dshsj = now;
					String vbz = "万里汇外币付款单,单号：" + entity.getBid() + "," + entity.getRemark() + "," + detail.getRemark();
					Date writeTime = now;
					tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(vgsbm, vgsjc, vgsbmp, vgsjcp, vjylx, fje, djysj, dshsj, vbz,entity.getBid(), writeTime);
				}
			}

			for(TcwWanliOtherPaymentItem detail : listTcwWanliOtherPaymentItem) {
				ThrOperateCompanyApply thrOperateCompanyApply = new ThrOperateCompanyApply().setVgsbm(detail.getVgsbm()).queryFirst();
				boolean isCheckCapital = false;
				String depositPlatformCode = entity.getDepositPlatformCode();
				String exchangeRateCode = entity.getCurrencyCodeOut();
				Integer documentType = 5;
				BigDecimal accountCount = detail.getAmount().add(detail.getFee()).setScale(2, BigDecimal.ROUND_HALF_UP).negate();
				String remark = "运营公司简称：" + thrOperateCompanyApply.getVgsjc() + "，付款类型：" + TcwWanliOtherPaymentEnum.PayType.getName(entity.getPayType()) + "，单号：" + entity.getBid() + "，本单备注：" + entity.getRemark();
				tcwAccountCountForWanliService.add(isCheckCapital, depositPlatformCode, exchangeRateCode, documentType,entity.getBid(), accountCount, remark);
			}


			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}





	/**
	 * 手动刷预付款退回流水
	 */
	@RequestMapping("/test5")
	@ResponseBody
	public R test5(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			List<TcwPaymentReturn> entityList = new TcwPaymentReturn()
					.where("A.Bid IN ('THSQ-241212-1019','THSQ-241216-1012','THSQ-241212-1003')")
					.setEffectStock(1)
					.queryList();
			for(TcwPaymentReturn entity :  entityList){

				logger.info("***********"+entity.getBid()+"***********");
				List<TcwPaymentReturnItem> tcwPaymentReturnItemList = new TcwPaymentReturnItem().setPaymentReturnBid(entity.getBid()).queryList();
				for (TcwPaymentReturnItem tcwPaymentReturnItem : tcwPaymentReturnItemList) {
					//查询运营公司银行账户
					ThrOperateCompanyBankInfo thrOperateCompanyBankInfo  = new ThrOperateCompanyBankInfo().setId(tcwPaymentReturnItem.getCompanyBankId()).queryFirst();

					//判断扣减运营预付款的金额
					TcwOperateCompanyPrepayment tcwOperateCompanyPrepayment = new TcwOperateCompanyPrepayment().setId(tcwPaymentReturnItem.getOperateCompanyPrepaymentId()).queryFirst();

					tcwOperateCompanyPrepayment.setPreReturnAmount(tcwOperateCompanyPrepayment.getPreReturnAmount().add(tcwPaymentReturnItem.getThAmount()));
					tcwOperateCompanyPrepayment.setPreResAmount(tcwOperateCompanyPrepayment.getPreResAmount().subtract(tcwPaymentReturnItem.getThAmount()));
					tcwOperateCompanyPrepaymentMapper.update(tcwOperateCompanyPrepayment);

					//查询对应收款账户的id
					TbCompanyBankInfo tbCompanyBankInfo = new TbCompanyBankInfo().setVid(tcwOperateCompanyPrepayment.getVid()).queryFirst();
					TbBaseInfo tcwFinancialTransactionTypeItem = tcwFinancialTransactionFlowService.getTransactionType(TransactionTypeEnum.FinanceType.TCW_PaymentReturn.name);


					//新增财务流水
					R res2 = tcwFinancialTransactionFlowService.add(true, tbCompanyBankInfo.getId(), tcwFinancialTransactionTypeItem.getBid(),
							thrOperateCompanyBankInfo.getVyhzhmc(), thrOperateCompanyBankInfo.getVkhh(), thrOperateCompanyBankInfo.getVyhzh(), tcwPaymentReturnItem.getThAmount().negate(),
							entity.getCreateTime(), entity.getUpdateTime(), entity.getUpdateTime(), "预付款退回申请：单号" + entity.getBid(),
							2, entity.getId());


				}
			}



			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}




	/**
	 * 手动刷预付款退回流水
	 */
	@RequestMapping("/test61")
	@ResponseBody
	public R test61(HttpServletRequest request, HttpServletResponse response
	) {
		try {
	{
		String bid = "WFRZ-250319-1001";
		TcwWanliPrepaymentRecorded entity = new TcwWanliPrepaymentRecorded().setBid(bid).queryFirst();

		Date theDate = new Date();
		entity.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
		entity.setUpdateTime(theDate);

		List<TcwWanliPrepaymentRecordedItem> itemList = new TcwWanliPrepaymentRecordedItem().setPbid(entity.getBid()).queryList();
		if(itemList!=null && itemList.size()>0){
			for(TcwWanliPrepaymentRecordedItem sonItem:itemList){
				logger.info("*******进行id="+sonItem.getId()+" 的关联操作*******");
				//获取对账单子表信息
				TcwWanliReconciliationItem tcwWanliReconciliationItem = new TcwWanliReconciliationItem().setId(sonItem.getReconciliationItemId()).queryFirst();
				if(tcwWanliReconciliationItem!=null){
					//预付款归集明细--对应数据标记为已付款
					TcwWanliPrepaymentPooling tcwWanliPrepaymentPooling = new TcwWanliPrepaymentPooling();
					//修改入账状态
					tcwWanliPrepaymentPooling.setRecordedStatus(1);//已入账
					tcwWanliPrepaymentPooling.setId(tcwWanliReconciliationItem.getWanliPrepaymentPoolingId());
					//tcwWanliPrepaymentPoolingMapper.update(tcwWanliPrepaymentPooling);

					//管理绩效逻辑产生交易流水
					//入账金额
					BigDecimal recordedAmount = sonItem.getRecordedAmount();
					logger.info("入账金额:"+recordedAmount);

					//明细信息
					Map<String,Object> poolingInfo = new TcwWanliPrepaymentPooling()
							//.addField("D.Vgsbm AS vgsbm")
							.addField("O.Vgsjc AS vgsjc")
							.addField("O.ManageRatio AS manageRatio")
							//.addLeftJoin("TCW_DepositPlatformAccount D ON D.Mid = A.FkMid")
							.addLeftJoin("THR_OperateCompanyApply O ON O.Vgsbm = A.Vgsbm")
							.setId(tcwWanliReconciliationItem.getWanliPrepaymentPoolingId())
							.queryFirstMap();

					String vgsbm = poolingInfo.get("vgsbm").toString();
					String vgsjc = poolingInfo.get("vgsjc").toString();
					BigDecimal manageRatio = BigDecimal.ZERO;//管理比例
					if(checkUtil.isNotNullByObject(poolingInfo.get("manageRatio"))){
						manageRatio = new BigDecimal(poolingInfo.get("manageRatio").toString());
					}

					//运营公司入账流水
					if(recordedAmount.compareTo(BigDecimal.ZERO)!=0){
						tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
								vgsbm,vgsjc,
								"HZZH0002", "AMAZON", TransactionTypeEnum.BusinessType.TCW_WanliPrepaymentRecorded_1.name,
								(recordedAmount.compareTo(BigDecimal.ZERO)<0?recordedAmount.abs():recordedAmount),
								theDate,theDate,
								"WF预付款入账单："+ bid + "，币种："+ poolingInfo.get("jyCurrencyCode") + "，记录归集金额："+ tcwWanliReconciliationItem.getRecordAmountGuiji(),
								null,theDate);

					}

					//*******15%到运营事业部*******
					BigDecimal recordedAmountCount15 = recordedAmount.multiply(new BigDecimal(0.15)).setScale(2, RoundingMode.HALF_UP);//保留2位小数
					if(recordedAmountCount15.compareTo(BigDecimal.ZERO)<0){
						recordedAmountCount15 = recordedAmountCount15.abs();
					}
					logger.info("15%到运营事业部:"+recordedAmountCount15);
					if(recordedAmountCount15.compareTo(BigDecimal.ZERO)!=0){
						//运营公司管理绩效支出流水（转账，两条数据）
						tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
								vgsbm,vgsjc,
								"GS0002", "运营事业部",TransactionTypeEnum.BusinessType.TCW_WanliPrepaymentRecorded_2.name,
								recordedAmountCount15.negate(),theDate,theDate,
								"管理绩效（15.00%），WF预付款入账单："+ bid + "，入账公司：" + vgsbm + vgsjc,
                                null,theDate);
						tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
								"GS0002", "运营事业部",
								poolingInfo.get("vgsbm").toString(),poolingInfo.get("vgsjc").toString(),
								TransactionTypeEnum.BusinessType.TCW_WanliPrepaymentRecorded_2.name,
								recordedAmountCount15,theDate,theDate,
								"管理绩效（15.00%），WF预付款入账单："+ bid + "，入账公司：" + vgsbm + vgsjc,
                                null,theDate);
					}

					//*******10%进行分配*******
					BigDecimal recordedAmountCount10 = recordedAmount.multiply(new BigDecimal(0.1)).setScale(2, RoundingMode.HALF_UP);//保留2位小数
					if(recordedAmountCount10.compareTo(BigDecimal.ZERO)<0){
						recordedAmountCount10 = recordedAmountCount10.abs();
					}
					logger.info("10%进行分配:"+recordedAmountCount10);
					BigDecimal remaining = BigDecimal.ZERO;//剩余培训费
					BigDecimal trainingFees = BigDecimal.ZERO;//培训费标准
					BigDecimal gfJe = BigDecimal.ZERO;//已收培训费
					BigDecimal gfJeByNew = BigDecimal.ZERO;//新已收培训费
					BigDecimal gfJeByAdd = BigDecimal.ZERO;//收到的培训费
					//获取对应运营公司的，培训费信息
					ThrOperateCompanyApply thrOperateCompanyApply = new ThrOperateCompanyApply().setVgsbm(vgsbm).queryFirst();
					if(thrOperateCompanyApply!=null){
						if(checkUtil.isNotNullByObject(thrOperateCompanyApply.getTrainingFees()))trainingFees = thrOperateCompanyApply.getTrainingFees();
						if(checkUtil.isNotNullByObject(thrOperateCompanyApply.getGfJe()))gfJe = thrOperateCompanyApply.getGfJe();
					}
					logger.info("培训费标准:"+trainingFees+"，已收培训费:"+gfJe);
					BigDecimal deductTrainingFees = trainingFees.subtract(gfJe);//可加的培训费数
					if(deductTrainingFees.compareTo(recordedAmountCount10)>=0 && deductTrainingFees.compareTo(BigDecimal.ZERO)!=0){//全部扣到培训费
						gfJeByNew = gfJe.add(recordedAmountCount10);
						gfJeByAdd = recordedAmountCount10;//收到的培训费 = 分配金额
					}else {//全部扣完培训费还有剩余
						remaining = recordedAmountCount10.subtract(deductTrainingFees);
						gfJeByNew = trainingFees;
						gfJeByAdd = deductTrainingFees;//收到的培训费 = 可加的培训费数
					}
					if(thrOperateCompanyApply!=null){
						thrOperateCompanyApply.setGfJe(gfJeByNew);
						thrOperateCompanyApplyMapper.update(thrOperateCompanyApply);//修改已收培训费
					}
					logger.info("剩余培训费:"+remaining+"，新已收培训费:"+gfJeByNew+"，收到的培训费:"+gfJeByAdd);
					if(gfJeByAdd.compareTo(BigDecimal.ZERO)<=0){
						logger.info("公司:"+vgsbm+"，收到的培训费计算出来小于0");
					}
					if(gfJeByAdd.compareTo(BigDecimal.ZERO)!=0 && gfJeByAdd.compareTo(BigDecimal.ZERO)>0){
						//培训费流水
						tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
								"GS0002","运营事业部","GS0856", "运营支持中心",
								TransactionTypeEnum.BusinessType.TCW_WanliPrepaymentRecorded_3.name,gfJeByAdd.negate(),theDate,theDate,
								"WF预付款入账单："+ bid + "，入账公司：" + vgsbm + vgsjc,
                                null,theDate);
						tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
								"GS0856", "运营支持中心","GS0002","运营事业部",
								TransactionTypeEnum.BusinessType.TCW_WanliPrepaymentRecorded_3.name,gfJeByAdd,theDate,theDate,
								"WF预付款入账单："+ bid + "，入账公司：" + vgsbm + vgsjc,
                                null,theDate);
					}

					//*******管理绩效分配*******
					//如果还有剩余
					if(remaining.compareTo(BigDecimal.ZERO)>0){
						//hrMapper Map<String, Object> getParentCompanyInfo
						BigDecimal baseRatio = new BigDecimal(10);//基础比例是10%
						BigDecimal firstSubtractRatio = new BigDecimal(85);//第一个分配的公司管理比例减85%

						BigDecimal firstRatio = BigDecimal.ZERO;//第一家的最终比例
						BigDecimal secondRatio = BigDecimal.ZERO;//第二家的最终比例
						BigDecimal thirdRatio = BigDecimal.ZERO;//第三家的最终比例

						BigDecimal firstRatioCount = manageRatio.subtract(firstSubtractRatio);//第一家的比例差额
						BigDecimal secondRatioCount = BigDecimal.ZERO;
						BigDecimal thirdRatioCount = BigDecimal.ZERO;

						if(firstRatioCount.compareTo(baseRatio)>=0){//第一家的比例计算大于10%
							firstRatio = baseRatio;
							baseRatio = BigDecimal.ZERO;//剩余比例0
						}else{
							firstRatio = (firstRatioCount.compareTo(BigDecimal.ZERO)<0?BigDecimal.ZERO:firstRatioCount);
							baseRatio = baseRatio.subtract((firstRatioCount.compareTo(BigDecimal.ZERO)<0?BigDecimal.ZERO:firstRatioCount));//剩余比例 = 10% - 第一家的比例计算
						}
						logger.info("第一个分配的公司:"+vgsjc+"；管理比例:"+manageRatio+"；剩余比例："+baseRatio+"；最终比例:"+firstRatio);

						String vgsbmSecond = "";
						String vgsjcSecond = "";
						String vgsbmThird = "";
						String vgsjcThird = "";
						if(baseRatio.compareTo(BigDecimal.ZERO)>0){
							//上级计算***计算开始
							//获取上级公司编码
							Map<String, Object> getParentCompanyInfoSecond = hrMapper.getParentCompanyInfo(vgsbm);
							if(getParentCompanyInfoSecond!=null){
								vgsbmSecond = getParentCompanyInfoSecond.get("vgsbm").toString();
								vgsjcSecond = getParentCompanyInfoSecond.get("vgsjc").toString();
								if(vgsbmSecond.equals(vgsbm)){
									Map<String, Object> getParentCompanyInfoSecondByNew = hrMapper.getParentParentCompanyInfo(vgsbm);
									vgsbmSecond = getParentCompanyInfoSecondByNew.get("vgsbm").toString();
									vgsjcSecond = getParentCompanyInfoSecondByNew.get("vgsjc").toString();
								}

								ThrOperateCompanyApply companyApplySecond = new ThrOperateCompanyApply().setVgsbm(vgsbmSecond).queryFirst();
								if(companyApplySecond!=null){
									BigDecimal manageRatioSecond = BigDecimal.ZERO;//管理比例
									if(checkUtil.isNotNullByObject(companyApplySecond.getManageRatio())){
										manageRatioSecond = companyApplySecond.getManageRatio();
									}
									secondRatioCount = manageRatioSecond.subtract(manageRatio);//第二家的比例计算
									if(secondRatioCount.compareTo(baseRatio)>=0){//第二家的比例计算大于剩余比例
										secondRatio = baseRatio;
										baseRatio = BigDecimal.ZERO;//剩余比例0
									}else{
										secondRatio = (secondRatioCount.compareTo(BigDecimal.ZERO)<0?BigDecimal.ZERO:secondRatioCount);
										baseRatio = baseRatio.subtract((secondRatioCount.compareTo(BigDecimal.ZERO)<0?BigDecimal.ZERO:secondRatioCount));//剩余比例 = 剩余比例 - 第二家的比例计算
									}
									logger.info("第二个分配的公司:"+vgsjcSecond+"；管理比例:"+manageRatioSecond+"；剩余比例："+baseRatio+"；最终比例:"+secondRatio);
									//上上级***计算开始
									if(baseRatio.compareTo(BigDecimal.ZERO)>0){
										//上上级计算
										//获取上级公司编码
										Map<String, Object> getParentCompanyInfoThird = hrMapper.getParentCompanyInfo(vgsbmSecond);
										if(getParentCompanyInfoThird!=null){
											vgsbmThird = getParentCompanyInfoThird.get("vgsbm").toString();
											vgsjcThird = getParentCompanyInfoThird.get("vgsjc").toString();
											if(vgsbmThird.equals(vgsbmSecond)){
												Map<String, Object> getParentCompanyInfoThirdByNew = hrMapper.getParentParentCompanyInfo(vgsbmSecond);
												vgsbmThird = getParentCompanyInfoThirdByNew.get("vgsbm").toString();
												vgsjcThird = getParentCompanyInfoThirdByNew.get("vgsjc").toString();
											}

											ThrOperateCompanyApply companyApplyThird = new ThrOperateCompanyApply().setVgsbm(vgsbmThird).queryFirst();
											if(companyApplyThird!=null){
												BigDecimal manageRatioThird = BigDecimal.ZERO;//管理比例
												if(checkUtil.isNotNullByObject(companyApplyThird.getManageRatio())){
													manageRatioThird = companyApplyThird.getManageRatio();
												}
												thirdRatioCount = manageRatioThird.subtract(manageRatioSecond);//第三家的比例计算
												if(thirdRatioCount.compareTo(baseRatio)>=0){//第三家的比例计算大于剩余比例
													thirdRatio = baseRatio;
													//baseRatio = BigDecimal.ZERO;//剩余比例0
												}else{
													thirdRatio = (thirdRatioCount.compareTo(BigDecimal.ZERO)<0?BigDecimal.ZERO:thirdRatioCount);
													//baseRatio = baseRatio.subtract(secondThirdCount);//剩余比例 = 剩余比例 - 第三家的比例计算
												}
												logger.info("第三个分配的公司:"+vgsjcThird+"；管理比例:"+manageRatioThird+"；最终比例:"+thirdRatio);
											}

										}
									}
									//上上级***计算结束
								}
							}
						}
						//上级***计算结束
						logger.info("第一家的最终比例:"+firstRatio+"，第二家的最终比例:"+secondRatio+"，第三家的最终比例:"+thirdRatio);
						//根据各家比例计算分配的金额
						BigDecimal firstAmount = BigDecimal.ZERO;
						BigDecimal secondAmount = BigDecimal.ZERO;
						BigDecimal thirdAmount = BigDecimal.ZERO;
						if(firstRatio.compareTo(BigDecimal.ZERO)>0){
							firstAmount = recordedAmount.multiply(firstRatio).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);//保留2位小数，四舍五入
						}
						if(secondRatio.compareTo(BigDecimal.ZERO)>0){
							secondAmount = recordedAmount.multiply(secondRatio).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);//保留2位小数，四舍五入
						}
						if(thirdRatio.compareTo(BigDecimal.ZERO)>0){
							thirdAmount = recordedAmount.multiply(thirdRatio).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);//保留2位小数，四舍五入
						}
						logger.info("第一家计算:"+firstAmount+"，第二家计算:"+secondAmount+"，第三家计算:"+thirdAmount);
						//新增流水
						if(firstAmount.compareTo(BigDecimal.ZERO)>0){
							tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
									"GS0002","运营事业部",vgsbm, vgsjc,
									TransactionTypeEnum.BusinessType.TCW_WanliPrepaymentRecorded_4.name,
									firstAmount.negate(),theDate,theDate,
									"管理绩效（"+firstRatioCount+"），WF预付款入账单："+ bid + "，入账公司：" + vgsbm + vgsjc,
                                    null,theDate);

							tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
									vgsbm, vgsjc,"GS0002","运营事业部",
									TransactionTypeEnum.BusinessType.TCW_WanliPrepaymentRecorded_4.name,
									firstAmount,theDate,theDate,
									"管理绩效（"+firstRatioCount+"），WF预付款入账单："+ bid + "，入账公司：" + vgsbm + vgsjc,
                                    null,theDate);
						}
						if(secondAmount.compareTo(BigDecimal.ZERO)>0){
							tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
									"GS0002","运营事业部",vgsbmSecond, vgsjcSecond,
									TransactionTypeEnum.BusinessType.TCW_WanliPrepaymentRecorded_4.name,
									secondAmount.negate(),theDate,theDate,
									"管理绩效（"+secondRatioCount+"），WF预付款入账单："+ bid + "，入账公司：" + vgsbm + vgsjc,
                                    null,theDate);

							tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
									vgsbmSecond, vgsjcSecond,"GS0002","运营事业部",
									TransactionTypeEnum.BusinessType.TCW_WanliPrepaymentRecorded_4.name,
									secondAmount,theDate,theDate,
									"管理绩效（"+secondRatioCount+"），WF预付款入账单："+ bid + "，入账公司：" + vgsbm + vgsjc,
                                    null,theDate);
						}
						if(thirdAmount.compareTo(BigDecimal.ZERO)>0){
							tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
									"GS0002","运营事业部", vgsbmThird, vgsjcThird,
									TransactionTypeEnum.BusinessType.TCW_WanliPrepaymentRecorded_4.name,
									thirdAmount.negate(),theDate,theDate,
									"管理绩效（"+thirdRatioCount+"），WF预付款入账单："+ bid + "，入账公司：" + vgsbm + vgsjc,
                                    null,theDate);

							tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
									vgsbmThird, vgsjcThird,"GS0002","运营事业部",
									TransactionTypeEnum.BusinessType.TCW_WanliPrepaymentRecorded_4.name,
									thirdAmount,theDate,theDate,
									"管理绩效（"+thirdRatioCount+"），WF预付款入账单："+ bid + "，入账公司：" + vgsbm + vgsjc,
                                    null,theDate);
						}

					}

//					//新增：运营公司预付款管理
//					R res = tcwOperateCompanyPrepaymentService.addOrAccrualWanliInfo(vgsbm,entity.getDepositPlatformCode(),sonItem.getRecordedAmount(),
//							BigDecimal.ZERO,BigDecimal.ZERO,BigDecimal.ZERO);
//					if(res.getCode().equals( R.Code.FAILED.value)){
//						throw new IllegalArgumentException(res.getMsg());
//					}
				}
			}
		}else{
			throw new IllegalArgumentException("未查询到对应的子表数据");
		}

		//按目标生成流水明细
		if(entity.getRecordedFinance().compareTo(BigDecimal.ZERO)!=0){
			tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
					"GS0889","问前集团",
					"HZZH0002", "AMAZON","经营费用→手续费",
					entity.getRecordedFinance(),theDate,theDate,
					"WF预付款入账单：单号："+ bid,
                    null,theDate);
		}

	}
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}
}
